package com.sf.tools.generate;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.sf.tools.common.CheckI18NProgressHandler;
import com.sf.tools.common.Common;

public class CheckFile {

	public static String LOG_MARK = "CHECK_I18N";
	
	private CheckI18NProgressHandler progressHandler;
	
	private List<String> fuhao = new ArrayList<String>();
	private List<String> regexs = new ArrayList<String>();
	
	private StringBuffer buff = new StringBuffer();
	
	public CheckFile(){
		fuhao.add("\'");
		fuhao.add("\"");
		
		regexs.add("\'.*\\s*[\u4e00-\u9fa5].*\'");
		regexs.add("\".*\\s*[\u4e00-\u9fa5].*\"");
	}
	
	private void print(String content){
		System.out.println(LOG_MARK+content);
	}
	
	@SuppressWarnings("serial")
	public void start(String path) {
		Common.files.clear();
		File f = new File(path);
		String saveLogPath = null;
		if(f.isDirectory()){
			saveLogPath = f.getPath();
		}else{
			saveLogPath = f.getParent();
		}
		File file = new File(saveLogPath + File.separator + "未国际化的内容.txt");
		
		List<String> suffix = new ArrayList<String>(){{
			add(".js");
		}};
		List<File> list = Common.findFilesByFileName(path, suffix, true);
//		System.out.println("count: "+list.size());
		this.progressHandler.loadTaskCount(list.size(),file);
		
		checkI18N(path);
		
		Common.write(file, buff.toString());
		print("检测完毕!");
		print("检查结果生成文件:"+file.getPath());
	}

	public void checkI18N(String path){
		
		File f = new File(path);
		if(!f.exists()) return ;
		if(f.isDirectory()){
			File[] files = f.listFiles();
			for (File file : files) {
				if(file.isFile() && file.getName().toLowerCase().endsWith(".js")){
					check(file);
				}else if(file.isDirectory()){
					checkI18N(file.getPath());
				}
			}
		}else if(f.isFile() && f.getName().toLowerCase().endsWith(".js")){
			check(f);
		}
	}
	
	/**
	 * 查找文件中需要国际化的汉字
	 * @param file
	 * @throws Exception
	 */
	private void check(File file) {
		try {
			this.progressHandler.doneTaskCount();
			print("正在检测:" + file.getPath());
			
			BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));
			String line = "";
			boolean comment = false;
			StringBuffer sb = new StringBuffer();
			int index = 0;
			while((line=br.readLine()) != null){
				index++;
				sb.append(line).append("\r\n");
				//去除注释
				line = line.trim();
				if(line.startsWith("/*") && !line.endsWith("*/")){
					comment = true;
					continue;
				}else if(line.startsWith("/*") && line.endsWith("*/")){
					continue;
				}else if(true == comment){
					if(line.endsWith("*/")){
						comment = false;
					}
					continue;
				}else if(line.startsWith("//")){
					continue;
				}
				boolean flag = find(line);
				if(!flag){
//					System.out.println("正在检测:" + file.getPath() + "  第" + index +"行");
					buff.append(file.getPath() + "  第" + index +"行").append("\r\n");
				}
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 判断是够包含汉字，注释里面的不算
	 * @author 徐益森(sfhq217)
	 * @date 2012-9-28 
	 * @param line
	 * @return true 包含 false 不包含
	 */
	public boolean existHZ(String line){
		String str = line;
		if(line.indexOf("//") != -1){
			str = line.substring(0, line.indexOf("//"));
		}else if(line.indexOf("/*") != -1){
			str = line.substring(0, line.indexOf("/*")) + line.substring(line.indexOf("*/")+"*/".length());
		}
		for(int i=0;i<str.length();i++){
			byte[] b = (str.charAt(i)+"").getBytes();
			if(b.length>1){
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 统计字符串target中字符串str出现的次数
	 * @param target	源字符串
	 * @param str	子字符串
	 * @return
	 */
	public int findCount(String target, String str){
		int oldLength = target.length();
		target = target.replace(str, "");
		int newLength = target.length();
		int count = (oldLength - newLength)/(str.length());
		return count;
	}
	
	/**
	 * 查找字符串string中子字符串str第n次出现的索引
	 * @author 徐益森(sfhq217)
	 * @date 2012-9-28 
	 * @param string
	 * @param str
	 * @param n
	 * @return
	 */
	public int findIndex(String string, String str, int n){
		int count =0;
		for(int i=0;i<string.length();i++){
			if(str.equals(string.charAt(i)+"")){
				count++;
				if(count == n){
					return i;
				}
			}
		}
		return 0;
	}
	
	/**
	 * //判断该字符串是否已经经过国际化处理
	 * @author 徐益森(sfhq217)
	 * @date 2012-9-29 
	 * @param list
	 * @param cc
	 * @return
	 */
	public boolean isI18N(String list, String cc){
		list = list.replace("(", "[(]")
				   .replace(")", "[)]")
				   .replace("?", "[?]")
				   .replace("*", "[*]");
		String regex = "";
		try {
			for(String fh : fuhao){
				regex = ".*[$][{]app:i18n_def[(].+,"+fh+list+fh+"\\s*[)][}]";

				Pattern p = Pattern.compile(regex);
				Matcher m = p.matcher(cc);
				if(m.find()) {
//					System.out.println("match");
					return true;
				}
			}
		} catch (Exception e) {
		}
		return false;
	}
	
	/**
	 * 是否国际化
	 */
	private boolean find(String line) {
		if(existHZ(line)){
			for(String regex : regexs){
				Pattern p = Pattern.compile(regex);
				Matcher m = p.matcher(line);
				while(m.find()){
					String content = m.group();
					for(String fh : fuhao){
						int count = findCount(content,fh);
						if(count % 2 ==0){
							for(int i=1;i<=count;i=i+2){
								String str = content.substring(findIndex(content,fh,i),findIndex(content,fh,i+1)+1);
								if(existHZ(str)){
//									String s = "' <font color=\"red\"><b>提示：只有6级以上才会显示标记 </b></font> '";
									Pattern p1 = Pattern.compile("\\s*[<].+[>](.+?)[<][/].+[>]");
									Matcher m1 = p1.matcher(str);
									if(m1.find()){
										str = m1.group(1);
									}
									String s = str.replace(fh, "");//.trim();
									if(!isI18N(s,line)){
										if( s.indexOf("app:i18n_def") == -1){
//											System.out.println("s2:"+s);
//											System.out.println("line:"+line);
											return false;
										}
									}
								}
							}
						}
					}
				}
			}
		}
		return true;
	}

	public static void main(String[] args) {
//		checkI18N("D:\\workspace_sfmap\\vms\\web\\scripts\\vmsreport\\");
//		CheckFile c = new CheckFile();
//		c.start("D:\\aa\\I18N_vehicle.js");
//		boolean flag = c.isI18N("确定要删除吗?", "Ext.Msg.confirm(\"${app:i18n_def('aaa.13','提示')}\",\"${app:i18n_def('aaa.26','确定要删除吗?')}\",function(btn){");
//		System.out.println(flag);
		String list = "确定要删除吗.";
		String cc = "Ext.Msg.confirm(\"${app:i18n_def('aaa.13','提示')}\",\"${app:i18n_def('aaa.26','确定要删除吗.')}\",function(btn){";
//		String cc = "Ext.Msg.alert(\"${app:i18n_def('aaa.13','提示')}\",\"${app:i18n_def('aaa.24','请选择要删除的记录!')}\");";
		String regex = ".*[$][{]app:i18n_def[(].+,'"+list+"'\\s*[)][}]";

		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(cc);
		if(m.find()) {
			System.out.println("match");
		}
		
	}

	public CheckI18NProgressHandler getProgressHandler() {
		return progressHandler;
	}

	public void setProgressHandler(CheckI18NProgressHandler progressHandler) {
		this.progressHandler = progressHandler;
	}

}
